package cn.sdut.training.struts.interceptor;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.sdut.training.domain.User;
import cn.sdut.training.struts.UserAware;
import cn.sdut.training.web.action.LoginAction;
import cn.sdut.training.web.action.RegAction;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoginInterceptor implements Interceptor{

	private static final long serialVersionUID = -5259259624406021055L;
	private static Logger logger = Logger.getLogger(LoginInterceptor.class);
	
	@Override
	public void destroy() {
		
	}

	@Override
	public void init() {
		
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Object action = invocation.getAction();
		
		if(action instanceof LoginAction || action instanceof RegAction){
			return invocation.invoke();
		}
		Map<String, Object> sessionMap = ServletActionContext.getContext().getSession();
		Object user = sessionMap.get("user");
		//如果用户没有登录
		if(user == null){
			return Action.LOGIN;
		}else{//为Action注入用户
			if (action instanceof UserAware) {
				((UserAware) action).setUser((User) user);
			}
			return invocation.invoke();
		}
	}

}
